package bookStore.dao.business;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;

import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import bookStore.dao.DaoTemplate;
import bookStore.po.Review;

public class ReviewDaoImpl extends DaoTemplate implements ReviewDao{

	public ReviewDaoImpl(Connection connection) {
		super(connection);
		
	}

	@Override
	public List<Review> queryAll(int offset, int pageSize) {
		return null;
	}

	@Override
	public void save(Review t) {
		this.sql="insert into review values(null,?,?,?)";
		
		try {
			this.queryRunner.update(this.connection,sql, t.getUserId(), t.getBookId(),t.getScore());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Review get(int id) {
		return null;
	}

	@Override
	public long count() {
		return 0;
	}

	@Override
	public void update(Review t) {
	}

	@Override
	public void delete(int id) {
	}

	@Override
	public List<String> getOpinionByBookId(int bookId) {
		this.sql="select opinion from review where bookId=? order by id desc limit 0,10";
		List<String> result = null;
		try {
			result=this.queryRunner.query(connection, sql, new ColumnListHandler<String>(1), bookId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}

	@Override
	public Review getReviewByUserAndBook(int userId, int bookId) {
		this.sql="select * from review where userId=? and bookId=?";
		try {
			return this.queryRunner.query(connection, sql, new BeanHandler<>(Review.class), userId,bookId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public double getAvgScoreByBook(int bookId) {
		this.sql="select avg(score)  from review where bookId=?";
		try {
			
			BigDecimal temp = this.queryRunner.query(connection, sql, new ScalarHandler<BigDecimal>(1), bookId);
			if(temp!=null) {
				return temp.doubleValue();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0.0;
	}

}
